<template>
  <div id="pdfContent">
    御剑乘风来,除魔天地间!reports
    <div id="print">
      <img src="../assets/logo.png" alt="" />
      这是一张打印图片
    </div>

    <button v-print="'#print'">打印</button>
    <button @click="dataURLToBlob">打印11</button>
    <div>
      <div ref="pdfContent">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column fixed prop="date" label="日期" width="150"></el-table-column>
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="province" label="省份" width="120"></el-table-column>
          <el-table-column prop="city" label="市区" width="120"></el-table-column>
          <el-table-column prop="address" label="地址" width="300"></el-table-column>
          <el-table-column prop="zip" label="邮编" width="120"></el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
              <el-button type="text" size="small">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-button type="danger" @click="ExportSavePdf()">导出PDF</el-button>
    </div>

    <div v-for="(item, index) in list" :key="index">
      {{ item.name }}
    </div>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
  data() {
    return {
      tableData: [],
      list: [
        {
          name: 'aaa',
        },
        {
          name: 'bbbb',
        },
      ],
    }
  },
  methods: {
    dataURLToBlob(dataurl) {
      //ie 图片转格式

      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }

      return new Blob([u8arr], { type: mime })
    },
    printOut(name) {
      // 个人观察只是截取可见范围以及以下的区域，所以先将滚动条置顶

      $(window).scrollTop(0) // jQuery 的方法

      document.body.scrollTop = 0 // IE的

      document.documentElement.scrollTop = 0 // 其他

      this.downloadResult(name)
    },

    downloadResult(name) {
      let canvasID = document.body

      let a = document.createElement('a')

      html2canvas(canvasID).then((canvas) => {
        let dom = document.body.appendChild(canvas)

        dom.style.display = 'none'

        a.style.display = 'none'

        document.body.removeChild(dom)

        let blob = this.dataURLToBlob(dom.toDataURL('image/png'))

        a.setAttribute('href', URL.createObjectURL(blob))

        a.setAttribute('download', name + '.png')

        document.body.appendChild(a)

        a.click()

        URL.revokeObjectURL(blob)

        document.body.removeChild(a)
      })
    },
  },
}
</script>
<style scoped></style>
